<?php session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/static/db/connect.php');
/**
 * 极验 二次验证
 */
require_once dirname(dirname(__FILE__)) . '/admin/includes/plugin/class.geetestlib.php';
require_once dirname(dirname(__FILE__)) . '/admin/includes/plugin/config.php';
$GtSdk = new GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
$user_id = $_SESSION['user_id'];
$GtCheck = false;
echo $GtCheck;
if ($_SESSION['gtserver'] == 1) {
    $result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $user_id);
    if ($result) {
        $GtCheck = true;
    }
} else {
    if ($GtSdk->fail_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'])) {
        $GtCheck = true;
    }
}
// 第二次验证结束

$info = $_POST["info"];
if (isset($info) && $GtCheck) {
    $key = base64_encode(pack("H*", $info));
    $info = Rsa::privDecrypt($key, true);
    $arr = explode("-", $info);
    if (empty($arr[1])) {
        echo json_encode(array('code' => '100001', 'msg' => 'Incomplete information'));
    } else {
        $sql = " select password,salt,name from qt_admin WHERE login_name = '$arr[1]' AND status = '1' limit 1";
        $mysqli_result = $mysqli->query($sql);
        if ($mysqli_result && $mysqli_result->num_rows > 0) {
            $db_info = $mysqli_result->fetch_assoc();
            $mysqli_result->close();
            $in_passwd_sha = hash_hmac("sha256", $arr[0], $db_info['salt']);
            if ($in_passwd_sha == $db_info['password']) {
                // 添加session
                $_SESSION['adminName'] = $db_info['name'];
                $res = array('code' => '000000', 'msg' => 'suc');
                echo json_encode($res);
            } else {
                $res = array('code' => '100003', 'msg' => 'Incorrect password');
                echo json_encode($res);
            }
        } else {
            $res = array('code' => '100002', 'msg' => 'No admin');
            echo json_encode($res);
        }
    }
} else {
    echo json_encode(array('code' => '100001', 'msg' => 'Incomplete information'));
}
$mysqli->close();

class Salt
{
    /**
     * 创建base64处理的盐
     * @return string
     */
    function build()
    {
        return base64_encode(Salt::create_password(20));
    }

    /**
     * 随机生成指定长度的盐
     * @param int $pw_length
     * @return string
     */
    function create_password($pw_length = 8)
    {
        $randpwd = '';
        for ($i = 0; $i < $pw_length; $i++) {
            $randpwd .= chr(mt_rand(48, 122));
        }
        return $randpwd;
    }
}

class Rsa
{
    private static $PRIVATE_KEY = '-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCmHO3l29zp9GbMuZMP0zstRxUUFZyupvrpfME6C88Ih6hja+lG
FBeTdLAf2WcFYhtM9LgsAQAqI/+5xNebXFnui2t9sQa8ndIhjoZxLhLKLsRhcLv7
u2xB8GGTRNKgJT+ri2UM19R/l7PZ4KoxPtU76s5TM+//uMwYUlpSm2R6owIDAQAB
AoGBAJtK6Ey/YqOFTKWPx6A/xU7q6RXBrpzIlkG505rEd2RuDkoEFCzjk7bSm+Tq
hZlOwl8LWTIqLVE4HlY5Y6dmitspntiBXyB2DxCc2A/hSH8l81bgjqmRkKPtNNsF
YXRBHtRs+LOpJyg26+y1HJ2IdCdxUSLGKOQAle2xC7W10JshAkEA16SxJIq3nA+U
V+y7KvT4XTzgpsycuwf3iNtsemmPNeI6N1V7oVeBPKB49UXmbf1bq4w6rUaeocjr
38Z1IWycrwJBAMUzRvULnSlFxkX9nvm0iiykA0VsoStNfLzThGS1AVjqEDDKa8ie
cr1VYa8ZzliiDx9Ibgj2DTLqceVxfaKWxk0CQA3AJ7ePzON7rtbodornsgqn/h9E
vt3CRUuJymIH5yTldxbeMZL5NHl8NhpVybrLxBOtTnSMI0Nnv3q2efOWrGsCQH1u
CSMSGQvIcr3P/M9NM1oDlIUS/EyDw+SDEUHRE6NPda7jAb2gctDUvwZV/rbHlaDL
PBn9DxYkov9SuZuyFT0CQEUJN12qyJ6B8+zMdItReUILfEXLYvY6LaG3xoukCfZd
ZHbxWFW/ENO047lR+pG17Zx9OjVPIiQ3ZStr6QVodWQ=
-----END RSA PRIVATE KEY-----';
    private static $PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmHO3l29zp9GbMuZMP0zstRxUU
FZyupvrpfME6C88Ih6hja+lGFBeTdLAf2WcFYhtM9LgsAQAqI/+5xNebXFnui2t9
sQa8ndIhjoZxLhLKLsRhcLv7u2xB8GGTRNKgJT+ri2UM19R/l7PZ4KoxPtU76s5T
M+//uMwYUlpSm2R6owIDAQAB
-----END PUBLIC KEY-----';
    /**
     * 16进制
     * 公匙: A61CEDE5DBDCE9F466CCB9930FD33B2D471514159CAEA6FAE97CC13A0BCF0887A8636BE94614179374B01FD96705621B4CF4B82C01002A23FFB9C4D79B5C59EE8B6B7DB106BC9DD2218E86712E12CA2EC46170BBFBBB6C41F0619344D2A0253FAB8B650CD7D47F97B3D9E0AA313ED53BEACE5333EFFFB8CC18525A529B647AA3
     * 密匙: 9B4AE84CBF62A3854CA58FC7A03FC54EEAE915C1AE9CC89641B9D39AC477646E0E4A04142CE393B6D29BE4EA85994EC25F0B59322A2D51381E563963A7668ADB299ED8815F20760F109CD80FE1487F25F356E08EA99190A3ED34DB056174411ED46CF8B3A9272836EBECB51C9D887427715122C628E40095EDB10BB5B5D09B21
     */
    /**
     * 返回对应的私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privKey);
    }

    /**
     * 返回对应的公钥
     * @return resource
     */
    private static function getPublicKey()
    {
        $pubkey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($pubkey);
    }

    /**
     * 私钥加密
     * @param $data
     * @return null|string
     */
    public static function privEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data, $encrypted, self::getPrivateKey()) ? base64_encode($encrypted) : null;
    }


    /**
     * 私钥解密
     * @param $encrypted 密文（二进制格式且base64编码）
     * @param bool $fromjs 密文是否来源于JS的RSA加密
     * @return null|string
     */
    public static function privDecrypt($encrypted, $fromjs = FALSE)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $padding = $fromjs ? OPENSSL_NO_PADDING : OPENSSL_PKCS1_PADDING;
        if (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey(), $padding)) {
            return $fromjs ? trim(strrev($decrypted)) : $decrypted;
        }
        return null;
    }

    /**
     * 公匙加密
     * @param $data
     * @return string
     * @throws Exception
     */
    public static function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, self::getPublicKey()))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
        return $data;
    }
}
